<?php

require_once 'modules/Book/models/Book.php';
require_once 'modules/language/models/Lang.php';
require_once 'modules/content/models/Content.php';
require_once 'modules/book/models/Chapter.php';
require_once 'modules/content/models/ContentCategory.php';
require_once 'modules/book/models/Lecture.php';
require_once 'modules/question/models/Question.php';
require_once 'modules/question/models/Answer.php';
require_once 'modules/Exercise/models/Folder.php';
require_once 'modules/Exercise/Models/ExerciseLib.php';
require_once 'modules/Exercise/Models/ExerciseParameter.php';

class Book_AdminController extends Nine_Controller_Action_Admin {

    public function manageLectureAction() {
        $objLecture = new Models_Lecture();
        $objCat = new Models_ContentCategory();

        $this->view->headTitle(Nine_Language::translate('manage Lecture '));
        $this->view->menu = array('chapter', 'managelecture');


        $config = Nine_Registry::getConfig();
        $numRowPerPage = Nine_Registry::getConfig("defaultNumberRowPerPage");
        $currentPage = $this->_getParam("page", 1);
        $displayNum = $this->_getParam('displayNum', false);

        $data = $this->_getParam('data', array());



        /**
         * Get number of items per page
         */
        if (false === $displayNum) {
            $displayNum = $this->session->contentDisplayNum;
        } else {
            $this->session->contentDisplayNum = $displayNum;
        }
        if (null != $displayNum) {
            $numRowPerPage = $displayNum;
        }
        /**
         * Get condition
         */
        $condition = $this->_getParam('condition', false);
        if (false === $condition) {
            $condition = $this->session->lectureCondition;
        } else {
            $this->session->lectureCondition = $condition;
            $currentPage = 1;
        }
        if (false == $condition) {
            $condition = array();
        }

        /**
         * Get all categories
         */
        $this->view->allCats = $objCat->getAll()->toArray();

        /**
         * Get all contents
         */
        $allLectures = $objLecture->getAllLectures($condition, array('lecture_id DESC'), $numRowPerPage, ($currentPage - 1) * $numRowPerPage
        );
        //        echo '<pre>';print_r($allContent);die;
        /**
         * Count all contents
         */
        $count = count($objLecture->getAllLectures($condition));
        $tmp = array();
        foreach ($allLectures as $index => $item) {


            /**
             * Change date
             */
            if (0 != $item['created_date']) {
                $item['created_date'] = date($config['dateFormat'], $item['created_date']);
            } else {
                $item['created_date'] = '';
            }
            if (0 != $item['update_date']) {
                $item['update_date'] = date($config['dateFormat'], $item['update_date']);
            } else {
                $item['update_date'] = '';
            }

            array_push($tmp, $item);
        }
        $allContent = $tmp;

        /**
         * Prepare for template
         */
        $date = time();
        $date = date('d/m/Y', $date);

        $this->view->date = $date;

// 	echo "<pre>";print_r($allLectures);die;

        /**
         * Set values for tempalte
         */
        $this->setPagination($numRowPerPage, $currentPage, $count);
        $this->view->allLecture = $allLectures;
        $this->view->lectureMessage = $this->session->lectureMessage;
        $this->session->lectureMessage = null;
        $this->view->condition = $condition;
        $this->view->displayNum = $numRowPerPage;
        $this->view->fullPermisison = $this->checkPermission('see_content');
    }

    public function deleteChapterAction() {
        $objChapter = new Models_Chapter();
        /**
         * Check permission
         */
        //         if (false == $this->checkPermission('delete_input')) {
        //             $this->_forwardToNoPermissionPage();
        //             return;
        //         }

        $id = $this->_getParam('id', false);
        //        echo "<pre>";print_r($input);die;

        if (false == $id) {
            $this->_redirect('book/admin/manage-chapter');
        }

        $ids = explode('_', trim($id, '_'));

        try {
            foreach ($ids as $id) {

                $objChapter->delete(array('chapter_id=?' => $id));
            }
            $this->session->ChapterMessage = array(
                'success' => true,
                'message' => 'Deleted!'
            );
        } catch (Exception $e) {
            $this->session->ChapterMessage = array(
                'success' => false,
                'message' => 'Can not delete'
            );
        }
        $this->_redirect('book/admin/manage-chapter');
    }

    /**
     * Book
     */
    public function manageBookAction() {
        $group = Nine_Registry::getLoggedInGroupId();
        $this->view->group = $group;

//    	echo "<pre>";print_r($group);die;
        $objBook = new Models_Book();
        $objLang = new Models_Lang();
        /**
         * Check permission
         */
        if (false == $this->checkPermission('see_Book', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }

        $this->view->headTitle('Manage Book ');
        $this->view->menu = array('book', 'managebook');


        $config = Nine_Registry::getConfig();
        $numRowPerPage = Nine_Registry::getConfig("defaultNumberRowPerPage");
        $currentPage = $this->_getParam("page", 1);
        $displayNum = $this->_getParam('displayNum', false);

        /**
         * Update sorting
         */
        $data = $this->_getParam('data', array());
        foreach ($data as $id => $value) {
            $value = intval($value);
            if (1 > $value) {
                continue;
            }
            $objBook->update(array('sorting' => $value), array('Book_gid=?' => $id));
            $this->session->BookMessage = array(
                'success' => true,
                'message' => Nine_Language::translate("Book is edited successfully")
            );
        }




        /**
         * Update sorting
         */
        $data = $this->_getParam('data', array());


        /**
         * Get condition
         */
        $condition = $this->_getParam('condition', false);
        if (false === $condition) {
            $condition = $this->session->BookCondition;
        } else {
            $this->session->BookCondition = $condition;
        }
        if (false == $condition) {
            $condition = array();
        }



        /**
         * Get all Books
         */
        $allBook = $objBook->setAllLanguages(true)->getAllBooks($condition, array('book_gid DESC', 'book_id ASC'), $numRowPerPage, ($currentPage - 1) * $numRowPerPage);

//            echo "<pre>";print_r($allBook[0]);
//            die;
        $tmp = array();
        $tmp2 = false;
//         $tmpGid =
        if($allBook)
        {
        	$tmpGid = $allBook[0]['book_gid'];
        	foreach ($allBook as $index => $book) {
        	
        		/**
        		 * Change date
        		 */
        		if (0 != $book['created_date']) {
        			$book['created_date'] = date($config['dateFormat'], $book['created_date']);
        		} else {
        			$book['created_date'] = '';
        		}
        		if ($tmpGid != $book['book_gid']) {
        			$tmp[] = $tmp2;
        			$tmp2 = false;
        			$tmpGid = $book['book_gid'];
        		}
        		if (false === $tmp2) {
        			$tmp2 = $book;
        		}
        	
        		$tmp2['langs'][] = $book;
        	
        		if ($index == count($allBook) - 1) {
        			$tmp[] = $tmp2;
        		}
        	}
        	$allBook = $tmp;
        }
        
        /**
         * Prepare for template
         */
        $date = time();
        $date = date('d/m/Y', $date);

        $this->view->date = $date;


        /**
         * Set values for tempalte
         */
        $this->view->allBook = $allBook;
        $this->view->BookMessage = $this->session->BookMessage;
        $this->session->BookMessage = null;
        $this->view->condition = $condition;
        $this->view->fullPermisison = $this->checkPermission('see_Book');
    }

    public function manageChapterAction() {

        $objLang = new Models_Lang();
        $allLangs = $objLang->getAll(array('sorting ASC'))->toArray();
        $objChapter = new Models_Chapter();


        $this->view->headTitle('Manage Chapter');
        $this->view->menu = array('chapter', 'manageChapter');


        $config = Nine_Registry::getConfig();
        $numRowPerPage = Nine_Registry::getConfig("defaultNumberRowPerPage");
        $currentPage = $this->_getParam("page", 1);
        $displayNum = $this->_getParam('displayNum', false);

        /**
         * Update sorting
         */
        $data = $this->_getParam('data', array());



        /**
         * Get condition
         */
        $condition = $this->_getParam('condition', false);
        if (false === $condition) {
            $condition = $this->session->ChapterCondition;
        } else {
            $this->session->ChapterCondition = $condition;
        }
        if (false == $condition) {
            $condition = array();
        }



        /**
         * Get all chapters
         */
        $allChapters = $objChapter->setAllLanguages(true)->getAllChapter($condition, array('chapter_gid DESC', 'chapter_id ASC'), $numRowPerPage, ($currentPage - 1) * $numRowPerPage);

        $count = count($objChapter->setAllLanguages(true)->getAllChapter($condition));
        $tmp = array();
        $tmp2 = false;
        if($allChapters)
            $tmpGid = $allChapters[0]['chapter_gid'];
        foreach ($allChapters as $index => $chap) {

            /**
             * Change date
             */
            if (0 != $chap['created_date']) {
                $chap['created_date'] = date($config['dateFormat'], $chap['created_date']);
            } else {
                $chap['created_date'] = '';
            }
            if (0 != $chap['update_date']) {
                $chap['update_date'] = date($config['dateFormat'], $chap['update_date']);
            } else {
                $chap['update_date'] = '';
            }

            if ($tmpGid != $chap['chapter_gid']) {
                $tmp[] = $tmp2;
                $tmp2 = false;
                $tmpGid = $chap['chapter_gid'];
            }
            if (false === $tmp2) {
                $tmp2 = $chap;
            }
            $tmp2['langs'][] = $chap;
            if ($index == count($allChapters) - 1) {
                $tmp[] = $tmp2;
            }
        }
        $allChapters = $tmp;
//     	echo "<pre>";print_r($allChapters);die;
        //echo "<pre>";print_r();die;

        /**
         * Prepare for template
         */
        $date = time();
        $date = date('d/m/Y', $date);

        $this->view->date = $date;


        /**
         * Set values for tempalte
         */
        $this->view->allChapters = $allChapters;
        $this->view->ChapterMessage = $this->session->ChapterMessage;
        $this->session->ChapterMessage = null;
        $this->view->condition = $condition;
        $this->view->fullPermisison = $this->checkPermission('see_Book');
    }

    public function newBookAction() {

        $objQuestion = new Models_Question();
        $objLang = new Models_Lang();
        $objBook = new Models_Book();

        $objCatQuestion = new Models_ContentCategory();
        $allLangs = $objLang->getAll(array('sorting ASC'))->toArray();

        $data = $this->_getParam('data', false);
//          echo "<pre>";print_r($data);die;

        /**
         * Get all categories
         */
        $errors = array();
        $objChapter = new Models_Chapter();

        $all = $objChapter->getAll();
        $allChapter = $all->toArray();
//        echo "<pre>";print_r($allChapter);die;



        //tam
        //   echo "<pre>";print_r($allChapter);die;
        if (false !== $data) {
            /**
             * Insert new content
             */
            $allChapters = explode(",", $data['chapter_titles']);
            $chapter_ids = "0";
            if($data['chapter_titles']){
                foreach ($allChapters as $item) {

                    $id_chapter = $objChapter->getIdOrInsert($item);
    //     			if($id_chapter!= 0)
    //     			{
    //     				$questions = $data[$item];
    //     				$question_ids = "0";
    //     				foreach ($questions as $ques)
    //     				{
    //     					$question_ids = $question_ids . "_" . $ques;
    //     				}
    //     				$chap = $objChapter->getChapterById( $id_chapter );
    //     				$chap['question_ids'] = $question_ids;
    //     				$objChapter->update($chap, array('chapter_id=?' => $id_chapter));
    //     			}
                    $chapter_ids = $chapter_ids . "_" . $id_chapter;
//                    echo "<pre>";print_r($chapter_ids);die;
                }
            }

            $pgid = '-1';
            foreach ($allLangs as $index => $lang) {
                $newBook = array();
                $newBook['created_date'] = time();
                $newBook['chapter_ids'] = $chapter_ids;
                $newBook['title'] = $data[$lang['lang_id']]['title'];
                $newBook['lang_id'] = $lang['lang_id'];
                $id_i = $objBook->insert($newBook);
                if($pgid == '-1')
                    $pgid = $id_i;
                $newBook['book_gid'] = $pgid;
                $newBook['book_version'] = 1.0;
                $newBook['book_version'] = sprintf ("%.1f", $newBook['book_version']);
                $objBook->update($newBook, array('book_id=?' => $id_i));
            }


            

            //$objBook->update($newBook, array('book_id=?' => $pgid));





            /**
             * Message
             */
            $this->session->contentMessage = array(
                'success' => true,
                'message' => Nine_Language::translate('Content is created successfully.')
            );
            $this->_redirect('book/admin/manage-book');
        } else {
//            $data = array();
//            $name = $this->_getParam('name', false);
//            if (false == $name) {
//                $data = array();
//            } else {
//                $data['title'] = $name;
//            }
//
//            $unit = @current($objChapter->find($data['unit'])->toArray());
//            $data['unit'] = $unit['name'];
        }

        /**
         * Prepare for template
         */
        $allCatQuestions = $objCatQuestion->getAll()->toArray();
        $ListQuestion = array();
        foreach ($allCatQuestions as $key => $cat) {
            //echo "<pre>";print_r($in['full_text']);die;
            $allQuestion = $objQuestion->getQuestionByCatId($cat['content_category_gid']);
            if (count($allQuestion) > 0) {
                //echo "<pre>";print_r($allQuestion);die;
                $tmp_array = array('group' => $cat['name'], 'questions' => $allQuestion);
                array_push($ListQuestion, $tmp_array);
            }
        }
//           echo "<pre>";print_r($ListQuestion);die;
        $this->view->allChapters = $allChapter;
        $this->view->allCats = $ListQuestion;
        $this->view->allLangs = $allLangs;
        /**
         * Prepare for template
         */
        $date = time();
        $date = date('d/m/Y', $date);
        $this->view->menu = array('book', 'newbook');
    }

    public function newChapterAction() {

        $objQuestion = new Models_Question();
        $objCatQuestion = new Models_ContentCategory();
        $objLecture = new Models_Content();
        $data = $this->_getParam('data', false);
        $errors = array();
        $objChapter = new Models_Chapter();
        $objLang = new Models_Lang();
        $allLangs = $objLang->getAll(array('sorting ASC'))->toArray();
        $objFolder = new Models_Folder();
        
        $objExercise = new Models_ExerciseParameter() ;
        $objExerciseLib = new Models_ExerciseLib();
        
        
        $allFolder = $objFolder->getAll(array('title ASC'))->toArray();
        
        if (false !== $data) {
            /**
             * Insert new content
             */
         	
            
            if ($data['folder_ids']) {
                $folders = $data['folder_ids'];
                $folder_ids = "0";
                foreach ($folders as $fol) {
                    $folder_ids = $folder_ids . "_" . $fol;
                }
            }
//           echo "<pre>";print_r($data);die; 
            if (count($data['question_ids']) >0) {
                $questions = $data['question_ids'];
                $question_ids = "0";
                foreach ($questions as $ques) {
                    $question_ids = $question_ids . "_" . $ques;
                }
            }
            if ($data['lecture_ids']) {
                $lectures = $data['lecture_ids'];
                $lecture_ids = "0";
                foreach ($lectures as $lec) {
                    $lecture_ids = $lecture_ids . "_" . $lec;
                }
            }
            
            if ($data['exercise_ids']) {
            	$exercise = $data['exercise_ids'];
            	$exercise_ids = "0";
            	foreach ($exercise as $exer) {
            		$exercise_ids = $exercise_ids . "_" . $exer;
            	}
            }

            $newChapter = array();
//echo "<pre>";print_r($data);die;
            $newChapter['question_ids'] = $question_ids;
            $newChapter['lecture_ids'] = $lecture_ids;
            $newChapter['folder_ids'] = $folder_ids;
            $newChapter['exercise_ids'] = $exercise_ids;
            $newChapter['created_date'] = time();
            $newChapter['update_date'] = time();
            $newChapter['subject_id'] = $data['subject_id'];
//         		echo "<pre>";print_r($data);die;
            foreach ($allLangs as $index => $lang) {
                $newChapter[$lang['lang_id']]['name'] = $data[$lang['lang_id']]['name'];
            }
//         		echo "<pre>";print_r($newChapter);die;
            $pgid = $objChapter->insert($newChapter);


            /**
             * Message
             */
            $this->session->contentMessage = array(
                'success' => true,
                'message' => Nine_Language::translate('Chapter is created successfully.')
            );
            $this->_redirect('book/admin/manage-chapter');
        } else {
            
        }

        /**
         * Prepare for template
         */
        $allCats = $objCatQuestion->getAllCategories(1,array('sorting ASC'));
     	$allSubjects =   $objCatQuestion->buildTree($objCatQuestion->getAllCategories(1,array('sorting ASC')));
        $allExerciseCat = $objExerciseLib->getAll()->toArray();
        
        $ListQuestion = array();
         $tmp_array = array();
        foreach ($allCats as $key => $cat) {
            $allQuestion = $objQuestion->getQuestionByCatId($cat['content_category_gid']);
            if (count($allQuestion) > 0) {
                $tmp_array = array('group' => $cat['name'], 'questions' => $allQuestion);
                array_push($ListQuestion, $tmp_array);
            }
        }
//        echo "<pre>";print_r($allCats);die;
        $ListDemo = array();
        $tmp_array = array();
        foreach ($allCats as $key => $cat) {
            $allFolderCat = $objFolder->getFolderByCatId($cat['content_category_gid']);
            if (count($allFolderCat) > 0) {
//                echo "<pre>";print_r($allFolderCat);die;
                $tmp_array = array('group' => $cat['name'], 'folders' => $allFolderCat);
                array_push($ListDemo, $tmp_array);
            }
        }
//      echo "<pre>";print_r($ListDemo);die;
        $ListLecture = array();
        $tmp_array = array();
        foreach ($allCats as $key => $cat) {
        	if($cat['content_category_gid'] != 1)
        	{
        		$allLectures = $objLecture->getContentByCatGid($cat['content_category_gid']);
        		if (count($allLectures) > 0) {
        			$tmp_array2 = array('group' => $cat['name'], 'lectures' => $allLectures);
        			array_push($ListLecture, $tmp_array2);
        		}
        	}
            
        }
        
        $ListExercise = array();
        $tmp_array = array();
        foreach ($allExerciseCat as $key => $exCat) {
        	
        		$allExercises = $objExercise->getExerciseByCatGid($exCat['exercise_lib_id']);
//         		echo "<pre>";print_r($allExercises);die;
        		if (count($allExercises) > 0) {
        			$tmp_array2 = array('group' => $exCat['name'], 'exercises' => $allExercises);
        			array_push($ListExercise, $tmp_array2);
        		}
        	
        
        }
        


//        echo "<pre>";print_r($ListExercise);die;

        $this->view->allSubjects = $allSubjects;
        $this->view->allCats = $ListQuestion;
        $this->view->allCatLecture = $ListLecture;
        $this->view->allLangs = $allLangs;
        $this->view->data = $data;
        $this->view->allFolder = $allFolder;
        $this->view->allDemoCat = $ListDemo;
        $this->view->allExerciseCat = $ListExercise;
        $this->view->menu = array('chapter', 'managechapter');
        
        /**
         * Prepare for template
         */
        $date = time();
        $date = date('d/m/Y', $date);
//        echo "<pre>";print_r($allUnit);die;
    }

    public function editBookAction() {
        $objBook = new Models_Book();
        $objLang = new Models_Lang();
        $allLangs = $objLang->setAllLanguages(true)->getAll(array('sorting ASC'))->toArray();
        $objChapter = new Models_Chapter();
        $objCatQuestion = new Models_ContentCategory();
        $objQuestion = new Models_Question();

        /**
         * Check permission
         */
        /* if (false == $this->checkPermission('edit_Book', null, '?')) {
          $this->_forwardToNoPermissionPage();
          return;
          } */

        $gid = $this->_getParam('id', false);
//         echo '<pre>';print_r($gid);die;
        if (false == $gid) {
            $this->_redirect('book/admin/manage-book');
        }

        $allChapterLangs = $objBook->setAllLanguages(true)->getByColumns(array('book_gid=?' => $gid))->toArray();
//        echo '<pre>';print_r($allChapterLangs);die;
        /**
         * Check permission
         */
        /* if ((false == $lid && false == $this->checkPermission('edit_Book', null, '*'))
          ||  (false != $lid && false == $this->checkPermission('edit_Book', null, $lid))) {
          $this->_forwardToNoPermissionPage();
          return;
          }
         */
        $data = $this->_getParam('data', false);
        $data2 = $this->_getParam('data2', false);
        /**
         * Get all Book languages
         */

        $errors = array();
        $bookChapters = array();
        if (false !== $data) {
//            echo "<pre>";print_r($data); print_r($gid);die;
            /**
             * Insert new Book
             */
            $newBook = $data;
            /**
             * Change format date
             */
//     		try {
            /**
             * Update
             */
            //tam
//     			            	echo '<pre>';print_r($newBook);die;

            $allChapters = explode(",", $data['chapter_titles']);
            $chapter_ids = "0";

//     		echo "<pre>";print_r($data);die;
            if (count($allChapters) > 0) {
                foreach ($allChapters as $item) {
//     			 		echo "<pre>";print_r($item);die;
                    if ($item) {
                        $id_chapter = $objChapter->getIdOrInsert($item);
                        $chapter_ids = $chapter_ids . "_" . $id_chapter;
                    }
                }
            }

            $newBook = $objBook->getBookByGid($gid);
//            echo "<pre>";print_r($newBook);
            foreach($newBook as $key => $book){
                $book['update_date'] = time();
                $book['chapter_ids'] = $chapter_ids;
                $book['title'] = $data[$book['lang_id']]['title'];
                if ($newBook[0]["chapter_ids"] != $chapter_ids) {
                    $book['book_version'] = $book['book_version'] + 0.1;
                    print_r($book['book_version']);
                }
                $objBook->update($book, array('book_id=?' => $book['book_id']));
                print_r($book);
            }

     		echo "<pre>";print_r($newBook);
//            print_r($chapter_ids);
//            print_r($newBook[0]["chapter_ids"]) ;
            ;die;

                /**
                 * Message
                 */
                $this->session->BookMessage = array(
                    'success' => true,
                    'message' => Nine_Language::translate('Book is updated successfully.')
                );
//            } catch (Exception $e) {
////                 $errors = array('main' => Nine_Language::translate('Can not insert into database now'));
//            }

            $this->_redirect('book/admin/manage-book');
//     		} catch (Exception $e) {
//     		}
        } else {
            echo "else";
            /**
             * Get old data
             */
            $data = @reset($allChapterLangs);
            foreach ($allChapterLangs as $content) {
                /**
                 * Rebuild readmore DIV
                 */
                //             	$content['full_text'] = Nine_Function::combineTextWithReadmore($content['intro_text'], $content['full_text']);
                $data[$content['lang_id']] = $content;
            }
            // load chapter of book
            $chaps = $data['chapter_ids'];
            $chapters = explode("_", $chaps);
//            echo "<pre>";print_r($data);

            if (count($chapters) > 1) {
                foreach ($chapters as $id) {
                    if ($id != 0) {
                    $chap = $objChapter->getChapterById($id);

                    //	$info = array('chapter' => $chap, 'questions' => $book_questions);
                    array_push($bookChapters, $chap);
                    }
                }
            }
//            echo "<pre>";print_r($chapters);die;

            if (false == $data) {
                $this->session->BookMessage = array(
                    'success' => false,
                    'message' => Nine_Language::translate("Book doesn't exist.")
                );
                $this->_redirect('book/admin/manage-book');
            }

            /**
             * Format image
             */
        }
        //        echo "<pre>";print_r($data);die;




        /**
         * Prepare for template
         */
        $allCatQuestions = $objCatQuestion->getAll()->toArray();
        $ListQuestion = array();
        foreach ($allCatQuestions as $key => $cat) {
//            echo "<pre>";print_r($in['full_text']);die;
            $allQuestion = $objQuestion->getQuestionByCatId($cat['content_category_gid']);
            if (count($allQuestion) > 0) {
                //echo "<pre>";print_r($allQuestion);die;
                $tmp_array = array('group' => $cat['name'], 'questions' => $allQuestion);
                array_push($ListQuestion, $tmp_array);
            }
        }






        $all = $objChapter->getAll();
        $allChapter = $all->toArray();
//          echo "<pre>";print_r($bookChapters);die;
        $this->view->allChapters = $allChapter;
        $this->view->allCats = $ListQuestion;
        $this->view->bookChapters = $bookChapters;
        $this->view->errors = $errors;
        $this->view->data = $data;
        $this->view->allLangs = $allLangs;
        $this->view->headTitle(Nine_Language::translate('Edit Book'));
        $this->view->menu = array('book', 'editbook');
        $this->view->fullPermisison = $this->checkPermission('edit_Book', null, '*');
    }

    public function editChapterAction() {
        $objChapter = new Models_Chapter();
        $objCatQuestion = new Models_ContentCategory();
        $objQuestion = new Models_Question();
        $objLecture = new Models_Content();
        $objFolder = new Models_Folder();
        $objLang = new Models_Lang();
        $allLangs = $objLang->setAllLanguages(true)->getAll(array('sorting ASC'))->toArray();
       // $allCats = 
        $allCats = $objCatQuestion->getAllCategories(1,array('sorting ASC'));
        $allSubjects =   $objCatQuestion->buildTree($objCatQuestion->getAllCategories(1,array('sorting ASC')));
        
      //  $objCatQuestion->getAll()->toArray();
        $objFolder = new Models_Folder();
        
        $allFolder = $objFolder->getAll(array('title ASC'))->toArray();
        $objExercise = new Models_ExerciseParameter() ;
        $objExerciseLib = new Models_ExerciseLib();
        
        $allExerciseCat = $objExerciseLib->getAll()->toArray();
        
        /**
         * Check permission
         */
        /* if (false == $this->checkPermission('edit_Book', null, '?')) {
          $this->_forwardToNoPermissionPage();
          return;
          } */

        $gid = $this->_getParam('id', false);
        // echo '<pre>';print_r($gid);die;
        if (false == $gid) {
            $this->_redirect('book/admin/manage-chapter');
        }
        $allChapterLangs = $objChapter->setAllLanguages(true)->getByColumns(array('chapter_gid=?' => $gid))->toArray();
        /**
         * Check permission
         */
        /* if ((false == $lid && false == $this->checkPermission('edit_Book', null, '*'))
          ||  (false != $lid && false == $this->checkPermission('edit_Book', null, $lid))) {
          $this->_forwardToNoPermissionPage();
          return;
          }
         */
        $data = $this->_getParam('data', false);
//         echo "<pre>";print_r($allChapterLangs);die;


        $errors = array();
        if (false !== $data) {
            /**
             * Insert new chapter
             */
            $newChapter = $data;
            /**
             * Change format date
             */
//            echo "<pre>";print_r($datas);die;
            $newChapter['update_date'] = time();
            if ($data['question_ids']) {
                $questions = $data['question_ids'];
                $question_ids = "0";
                foreach ($questions as $ques) {
                    $question_ids = $question_ids . "_" . $ques;
                }
            }
            
            if ($data['folder_ids']) {
                $folders = $data['folder_ids'];
                $folder_ids = "0";
                foreach ($folders as $fol) {
                    $folder_ids = $folder_ids . "_" . $fol;
                }
            }

            if ($data['lecture_ids']) {
                $lectures = $data['lecture_ids'];
                $lecture_ids = "0";
                foreach ($lectures as $lec) {
                    $lecture_ids = $lecture_ids . "_" . $lec;
                }
            }
            if ($data['folder_ids']) {
            	$folders = $data['folder_ids'];
            	$folder_ids = "0";
            	foreach ($folders as $fol) {
            		$folder_ids = $folder_ids . "_" . $fol;
            	}
            }
            if ($data['exercise_ids']) {
            	$exercises = $data['exercise_ids'];
            	$exercise_ids = "0";
            	foreach ($exercises as $ex) {
            		$exercise_ids = $exercise_ids . "_" . $ex;
            	}
            }
            

            // = $objChapter->getChapterById( $id_chapter );
            $newChapter['question_ids'] = $question_ids;
            $newChapter['lecture_ids'] = $lecture_ids;
            $newChapter['exercise_ids'] = $exercise_ids;
            $newChapter['folder_ids'] = $folder_ids;
            $newChapter['created_date'] = time();
            $newChapter['update_date'] = time();
            $newChapter['subject_id'] = $data['subject_id'];
            foreach ($allLangs as $index => $lang) {
                $newChapter[$lang['lang_id']]['name'] = $data[$lang['lang_id']]['name'];
            }

            try {
                /**
                 * Update
                 */
                //tam
//             	echo '<pre>';print_r($newChapter);die;
                $pgid = $objChapter->update($newChapter, array('chapter_gid=?' => $gid));

                /**
                 * Message
                 */
                $this->session->ChapterMessage = array(
                    'success' => true,
                    'message' => Nine_Language::translate('Chapter is updated successfully.')
                );

                $this->_redirect('book/admin/manage-chapter');
            } catch (Exception $e) {
//                 $errors = array('main' => Nine_Language::translate('Can not insert into database now'));
            }
        } else {
            /**
             * Get old data
             */
            $data = @reset($allChapterLangs);
//             echo "<pre>";print_r($data);die;
            if (false == $data) {
                $this->session->ChapterMessage = array(
                    'success' => false,
                    'message' => Nine_Language::translate("Chapter doesn't exist.")
                );
                $this->_redirect('book/admin/manage-chapter');
            }
            foreach ($allChapterLangs as $content) {
                /**
                 * Rebuild readmore DIV
                 */
//             	$content['full_text'] = Nine_Function::combineTextWithReadmore($content['intro_text'], $content['full_text']);
                $data[$content['lang_id']] = $content;
            }

            /**
             * Add deleteable field
             */
            if (null != @$data['content_category_gid']) {
                $cat = @reset($objCatQuestion->getByColumns(array('content_category_gid' => $data['subject_id']))->toArray());
                $data['content_deleteable'] = @$cat['content_deleteable'];
            }

            // load question

            $ques = explode("_", $data['question_ids']);
            $this->view->allQuestions = $ques;

            $lec = explode("_", $data['lecture_ids']);
            $this->view->allLectures = $lec;
            
            $demo = explode("_", $data['folder_ids']);
            $this->view->allDemos = $demo;
            
            $exer = explode("_", $data['exercise_ids']);
            $this->view->allExercises = $exer;
            
//             echo "<pre>";print_r($lec);die;
//            echo "<pre>";print_r($lec);die;
        }


        /**
         * Prepare for template
         */
        $allCatQuestions = $objCatQuestion->setAllLanguages(false)->getAll()->toArray();
        
        $ListDemo = array();
        $tmp_array = array();
        foreach ($allCats as $key => $cat) {
        	$allFolderCat = $objFolder->getFolderByCatId($cat['content_category_gid']);
        	if (count($allFolderCat) > 0) {
        		//                echo "<pre>";print_r($allFolderCat);die;
        		$tmp_array = array('group' => $cat['name'], 'folders' => $allFolderCat);
        		array_push($ListDemo, $tmp_array);
        	}
        }
//         echo "<pre>";print_r($ListDemo);die;
        $ListQuestion = array();
        $tmp_array = array();
        foreach ($allCatQuestions as $key => $cat) {
            //echo "<pre>";print_r($in['full_text']);die;
//         	echo "<pre>";print_r($cat['content_category_gid']);die;
            $allQuestion = $objQuestion->getAllEnabledQuestionsByCategory($cat['content_category_gid']);

            if (count($allQuestion) > 0) {
//         		echo "<pre>";print_r($allCatQuestions);die;
                $tmp_array = array('group' => $cat['name'], 'questions' => $allQuestion);
                array_push($ListQuestion, $tmp_array);
            }
        }
        
        $ListDemo = array();
        $tmp_array = array();
        foreach ($allCats as $key => $cat) {
            $allFolderCat = $objFolder->getFolderByCatId($cat['content_category_gid']);
            if (count($allFolderCat) > 0) {
//                echo "<pre>";print_r($allFolderCat);die;
                $tmp_array = array('group' => $cat['name'], 'folders' => $allFolderCat);
                array_push($ListDemo, $tmp_array);
            }
        }
        
        $ListExercise = array();
        $tmp_array = array();
        foreach ($allExerciseCat as $key => $exCat) {
        	 
        	$allExercises = $objExercise->getExerciseByCatGid($exCat['exercise_lib_id']);
        	//         		echo "<pre>";print_r($allExercises);die;
        	if (count($allExercises) > 0) {
        		$tmp_array2 = array('group' => $exCat['name'], 'exercises' => $allExercises);
        		array_push($ListExercise, $tmp_array2);
        	}
        	 
        
        }
        
        
//         echo "<pre>";print_r($ListQuestion);die;
        $ListLecture = array();
        $tmp_array = array();
        foreach ($allCatQuestions as $key => $cat) {
        	if($cat['content_category_gid'] != 1)
        	{
        		$allLectures = $objLecture->getContentByCatGid($cat['content_category_gid']);
        		if (count($allLectures) > 0) {
        			$tmp_array2 = array('group' => $cat['name'], 'lectures' => $allLectures);
        			array_push($ListLecture, $tmp_array2);
        		}
        	}
            //echo "<pre>";print_r($in['full_text']);die;
            
        }
//         echo "<pre>";print_r($ListQuestion);die;
        $this->view->allSubjects = $allSubjects;
        $this->view->allCats = $ListQuestion;
        $this->view->allCatLecture = $ListLecture;
        $this->view->allFolder = $allFolder;
        $this->view->allDemoCat = $ListDemo;
//         echo "<pre>";print_r($demo);die;
        $this->view->errors = $errors;
        $this->view->data = $data;
        $this->view->allLangs = $allLangs;
        $this->view->headTitle(Nine_Language::translate('Edit Chapter'));
        $this->view->menu = array('chapter', 'editchapter');
        $this->view->fullPermisison = $this->checkPermission('edit_Chapter', null, '*');
        $this->view->allDemoCat = $ListDemo;
        $this->view->allExerciseCat = $ListExercise;
    }

    public function deleteLectureAction() {
        $objLecture = new Models_Lecture();
        /**
         * Check permission
         */
        //         if (false == $this->checkPermission('delete_input')) {
        //             $this->_forwardToNoPermissionPage();
        //             return;
        //         }

        $id = $this->_getParam('id', false);
        //        echo "<pre>";print_r($input);die;

        if (false == $id) {
            $this->_redirect('book/admin/manage-lecture');
        }

        $ids = explode('_', trim($id, '_'));

        try {
            foreach ($ids as $id) {

                $objLecture->delete(array('lecture_id=?' => $id));
            }
            $this->session->ChapterMessage = array(
                'success' => true,
                'message' => 'Deleted!'
            );
        } catch (Exception $e) {
            $this->session->ChapterMessage = array(
                'success' => false,
                'message' => 'Can not delete'
            );
        }
        $this->_redirect('book/admin/manage-lecture');
    }

    public function deleteBookAction() {
        $objBook = new Models_Book();
        /**
         * Check permission
         */
//         if (false == $this->checkPermission('delete_input')) {
//             $this->_forwardToNoPermissionPage();
//             return;
//         }

        $id = $this->_getParam('id', false);
//        echo "<pre>";print_r($input);die;

        if (false == $id) {
            $this->_redirect('book/admin/manage-book');
        }

        $ids = explode('_', trim($id, '_'));

        try {
            foreach ($ids as $id) {

                $objBook->delete(array('book_gid=?' => $id));
            }
            $this->session->BookMessage = array(
                'success' => true,
                'message' => 'Deleted!'
            );
        } catch (Exception $e) {
            $this->session->BookMessage = array(
                'success' => false,
                'message' => 'Can not delete'
            );
        }
        $this->_redirect('book/admin/manage-book');
    }

    public function searchBookAction() {
        $objBook = new Models_Book();
        $group = Nine_Registry::getLoggedInGroupId();
        $this->view->group = $group;
        /**
         * Check permission
         */
        if (false == $this->checkPermission('search_Book', null, '?')) {
            $this->_forwardToNoPermissionPage();
            return;
        }
//        echo "<pre>";print_r($_POST);die;
        $this->view->headTitle('Thống kê giao dịch');
        $this->view->menu = array('Book', 'searchBook');


        $config = Nine_Registry::getConfig();
        $numRowPerPage = Nine_Registry::getConfig("defaultNumberRowPerPage");
        $currentPage = $this->_getParam("page", 1);
        $displayNum = $this->_getParam('displayNum', false);

        $objBook = new Models_Book();
        $errors = array();


        /**
         * Update sorting
         */
        $data = $this->_getParam('data', array());

        /**
         * Get number of items per page
         */
        if (false === $displayNum) {
            $displayNum = $this->session->BookDisplayNum;
        } else {
            $this->session->BookDisplayNum = $displayNum;
        }
        if (null != $displayNum) {
            $numRowPerPage = $displayNum;
        }
        /**
         * Get condition
         */
        $condition = $this->_getParam('condition', false);
        if (false === $condition) {
            $condition = $this->session->BookCondition;
        } else {
            $this->session->BookCondition = $condition;
            $currentPage = 1;
        }
        if (false == $condition) {
            $condition = array();
        }


//        $allBook = $objBook->getAllBooks($condition, array('Book_id DESC','update DESC'),
//                                                   $numRowPerPage,
//                                                   ($currentPage - 1) * $numRowPerPage
//                                                  );
        /**
         * Count all Books
         */
        $count = count($objBook->getAllBooks($condition));

        /**
         * Format
         */
//        foreach ($allBook as $index=> &$Book) {
//            /**
//             * Change date
//             */
//            if (0 != $Book['created_date']) {
//                $Book['created_date'] = date($config['dateFormat'], $Book['created_date']);
//            } else {
//                $Book['created_date'] = '';
//            }
//            
//            if($Book['unit']){
//                $objUnit = new Models_Unit();
//                $con['unit_id'] = $Book['unit'];
//                $unit =     $objUnit->getUnitById($Book['unit']);
//                
////                echo "<pre>";print_r($unit);die;
//                $Book['unit'] = $unit['name'];
////              echo "<pre>";print_r($Book);die;
//            }
//        }
//        unset($Book);

        $objInput = new Models_Input();

        $allInput = $objInput->getAllInputs($condition, array('created_date DESC'));
//        echo "<pre>";print_r($allInput);die;
        $objUnit = new Models_Unit();

        $objSale = new Models_Sale();
        $allSale = $objSale->getAllSales($condition, array('created_date DESC'));
//        echo "<pre>";print_r($allSale);die;
        foreach ($allInput as &$item) {
            if (0 != $item['created_date']) {
                $item['created_date'] = date($config['dateFormat'], $item['created_date']);
            } else {
                $item['created_date'] = '';
            }
            $Book = $objBook->getBookById($item['Book_id']);
            $item['Book_name'] = $Book['title'];
            $item['provider'] = $Book['provider'];
            $con['unit_id'] = $Book['unit'];
            $unit = $objUnit->getUnitById($Book['unit']);
            $item['unit'] = $unit['name'];
        }
        unset($item);
//        echo "<pre>";print_r($allInput);die;

        foreach ($allSale as &$sale) {
            if (0 != $sale['created_date']) {
                $sale['created_date'] = date($config['dateFormat'], $sale['created_date']);
            } else {
                $sale['created_date'] = '';
            }
            $Book = $objBook->getBookById($sale['Book_id']);
//            echo "<pre>";print_r($Book);die;
            $sale['Book_name'] = $Book['title'];
            $sale['provider'] = $Book['provider'];
            $con['unit_id'] = $Book['unit'];
            $unit = $objUnit->getUnitById($Book['unit']);
            $sale['unit'] = $unit['name'];
        }
        unset($sale);
//        echo "<pre>";print_r($allSale);die;
        $total = 0;
        $totalGiaBan = 0;
        foreach ($allInput as $item) {
            $total = $total + ($item['input_price'] * $item['soluong']);
            $totalGiaBan = $totalGiaBan + ($item['lsale_price'] * $item['soluong']);
        }
        $totalInSale = 0;
        $totalOuSale = 0;
        foreach ($allSale as $item1) {
            $totalInSale = $totalInSale + ($item1['sale_price'] * $item1['soluong']);
            $totalOuSale = $totalOuSale + ($item1['lsale_price'] * $item1['soluong']);
        }

        $this->view->allInputs = $allInput;
        $this->view->allSales = $allSale;

        $this->view->total = number_format($total, 0, ',', ' ');
        $this->view->totalGiaBan = number_format($totalGiaBan, 0, ',', ' ');
        $this->view->totalInSale = number_format($totalInSale, 0, ',', ' ');
        $this->view->totalOuSale = number_format($totalOuSale, 0, ',', ' ');


        /**
         * Prepare for template
         */
        $date = time();
        $date = date('d/m/Y', $date);

        $this->view->date = $date;

        /**
         * Set values for tempalte
         */
        $this->setPagination($numRowPerPage, $currentPage, $count);
        $this->view->datepickerFormat = Nine_Registry::getConfig('datepickerFormat');
        $this->view->BookMessage = $this->session->BookMessage;
        $this->session->BookMessage = null;
        $this->view->condition = $condition;
        $this->view->displayNum = $numRowPerPage;
        $this->view->fullPermisison = $this->checkPermission('see_Book');
    }

    public function enableBookAction() {
        $objBook = new Models_Book();
        $gid = $this->_getParam('gid', false);
        $lid = $this->_getParam('lid', false);

        if (false == $gid) {
            $this->_redirect('book/admin/manage-book');
        }

        $gids = explode('_', trim($gid, '_'));
        if (false == $lid) {
            /**
             * Change general status
             * Check full permission
             */
            if (false == $this->checkPermission('edit_Book', null, '*')) {
                $this->_forwardToNoPermissionPage();
                return;
            }
            try {
                foreach ($gids as $gid) {
                    $objBook->update(array('genabled' => 1), array('Book_gid=?' => $gid));
                }
                $this->session->BookMessage = array(
                    'success' => true,
                    'message' => Nine_Language::translate('Book is enable successfully')
                );
            } catch (Exception $e) {
                $this->session->BookMessage = array(
                    'success' => false,
                    'message' => Nine_Language::translate('Can NOT activate this Book. Please try again')
                );
            }
        } else {
            /**
             * Check permission on each language
             */
            if (false == $this->checkPermission('edit_Book', null, $lid)) {
                $this->_forwardToNoPermissionPage();
                return;
            }
            try {
                foreach ($gids as $gid) {
                    $objBook->update(array('enabled' => 1), array('Book_gid=?' => $gid, 'lang_id=?' => $lid));
                }
                $this->session->BookMessage = array(
                    'success' => true,
                    'message' => Nine_Language::translate('Book is enable successfully')
                );
            } catch (Exception $e) {
                $this->session->BookMessage = array(
                    'success' => false,
                    'message' => Nine_Language::translate('Can NOT activate this Book. Please try again')
                );
            }
        }


        $this->_redirect('Book/admin/manage-Book');
    }

    public function disableBookAction() {
        $objBook = new Models_Book();
        $gid = $this->_getParam('gid', false);
        $lid = $this->_getParam('lid', false);

        if (false == $gid) {
            $this->_redirect('Book/admin/manage-Book');
        }

        $gids = explode('_', trim($gid, '_'));
        if (false == $lid) {
            /**
             * Change general status
             * Check full permission
             */
            if (false == $this->checkPermission('edit_Book', null, '*')) {
                $this->_forwardToNoPermissionPage();
                return;
            }
            try {
                foreach ($gids as $gid) {
                    $objBook->update(array('genabled' => 0), array('Book_gid=?' => $gid));
                }
                $this->session->BookMessage = array(
                    'success' => true,
                    'message' => Nine_Language::translate('Book is disable successfully')
                );
            } catch (Exception $e) {
                $this->session->BookMessage = array(
                    'success' => false,
                    'message' => Nine_Language::translate('Can NOT deactive this Book. Please try again')
                );
            }
        } else {
            /**
             * Check permission on each language
             */
            if (false == $this->checkPermission('edit_Book', null, $lid)) {
                $this->_forwardToNoPermissionPage();
                return;
            }
            try {
                foreach ($gids as $gid) {
                    $objBook->update(array('enabled' => 0), array('Book_gid=?' => $gid, 'lang_id=?' => $lid));
                }
                $this->session->BookMessage = array(
                    'success' => true,
                    'message' => Nine_Language::translate('Book is disable successfully')
                );
            } catch (Exception $e) {
                $this->session->BookMessage = array(
                    'success' => false,
                    'message' => Nine_Language::translate('Can NOT deactive this Book. Please try again')
                );
            }
        }


        $this->_redirect('Book/admin/manage-Book');
    }

}